package cn.znzz.cjm.user.controller;

import cn.znzz.cjm.basic.exception.BusinessException;
import cn.znzz.cjm.basic.util.AjaxResult;
import cn.znzz.cjm.basic.util.PageList;
import cn.znzz.cjm.user.domain.User;
import cn.znzz.cjm.user.dto.UserDto;
import cn.znzz.cjm.user.query.UserQuery;
import cn.znzz.cjm.user.service.IUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门接口
 */
@RestController
@RequestMapping("/user")
@Api(value = "用户的接口",description = "用户接口详细描述")
public class UserController {
    @Autowired
    private IUserService userService;

    //dto用来接收前段传递的参数
    @PostMapping("/phone/register")
    public AjaxResult register(@RequestBody UserDto dto){
        try {
            userService.register(dto);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙");
        }
    }

    //新增或修改
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user){
        try {
            if (user.getId() == null){
                userService.add(user);
            }else {
                userService.update(user);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，稍后再试！");
        }
    }

    //删除
    @DeleteMapping("/{id}")
    public AjaxResult removeById(@PathVariable("id") Long id){
        try {
            userService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，稍后再试！");
        }
    }
    //批量删除  前段传的是数字，可以用list和数组接收
    @PatchMapping
    public AjaxResult BatchRemove(@RequestBody List<Long> ids){
        try {
            userService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，稍后再试！");
        }
    }

    //根据id查询
    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id){
        return userService.findById(id);
    }

    //查询所有
    @GetMapping
    public List<User> queryAll(){
        return userService.findAll();
    }

    //分页查询 高级查询
    @PostMapping("/list")
    public PageList<User> queryPage(@RequestBody UserQuery query){
        return userService.queryPage(query);
    }
}